local function utf8_sub(s, i, j)
    i = i or 1
    j = j or -1
    local n = utf8.len(s)
    if not n then return nil end
    if i < 1 or j < 1 then
        if i < 0 then i = n + 1 + i end
        if j < 0 then j = n + 1 + j end
        if i < 0 then i = 1 elseif i > n then i = n end
        if j < 0 then j = 1 elseif j > n then j = n end
    end
    if j < i then return "" end
    local oi = utf8.offset(s, i)
    local oj = utf8.offset(s, j + 1)
    if oi and oj then
        return s:sub(oi, oj - 1)
    elseif oi then
        return s:sub(oi)
    else
        return ""
    end
end

local codePrompt = {}

function codePrompt.init(env)
    local config = env.engine.schema.config
    local schema_id = config:get_string("schema/schema_id")
    env.reversedb = ReverseLookup(schema_id)
end

function codePrompt.tags_match(seg, env)
    local context = env.engine.context
    local status = context:get_option("code_prompt")
    return status and seg:has_tag("abc")
end

function codePrompt.func(input, env)
    for cand in input:iter() do
        if string.len(cand.text) < 1 then
            return nil
        end
        local cand_tail_text = utf8_sub(cand.text, -1, -1)
        local lookstr = env.reversedb:lookup(cand_tail_text) or ""
        local tail_char_hxm = utf8_sub(lookstr, -2, -1)
        local comment = (string.len(tail_char_hxm) > 0) and string.format('~%s', tail_char_hxm) or "~"
        cand.comment = comment
        yield(cand)
    end
end

return codePrompt